package com.study.jyg.rxjava2study.activity.wifidevicesearch.pingwifiip;

import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.strictmode.Violation;
import android.text.PrecomputedText;
import android.util.Log;

import com.study.jyg.rxjava2study.MyApplication;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;

public class NetToolTask extends AsyncTask<Integer, Integer, String> {


    private final int SERVERPORT = 8888 ;
    private final String PING = "ping -c 1 -w 0.5 " ; //其中 -c 1为发送的次数，-w 表示发送后等待响应的时间
    private Runtime run = Runtime.getRuntime(); //获取当前运行环境，来执行ping，相当于windows的cmd

    private Process proc = null ;

    private NetToolTaskListener netToolTaskListener;

    public void setNetToolTaskListener(NetToolTaskListener netToolTaskListener) {
        this.netToolTaskListener = netToolTaskListener;
    }

    /**
     * 开始执行任务
     */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();

    }

    /**
     * 后台运行
     * @param integers
     * @return
     */
    @Override
    protected String doInBackground(Integer... integers) {
        int ipEnd = integers[0];
        String locAddress = WifiUtils.getLocAddrIndex();
        String p = PING + locAddress + ipEnd ;
        String current_ip = locAddress+ ipEnd;
        boolean linkFlag = false;//是否链接成功
        boolean msgFlag = false;//是否发信息成功
        String msgResult = null;
        try {
            proc = run.exec(p);
            int result = proc.waitFor();
            if (result == 0 ) {
                linkFlag = true;
                Log.e("NetTool", "连接成功" + current_ip);
                // 向服务器发送验证信息
                String msg = sendMsg(current_ip, "scan" +WifiUtils.getIPAddress(MyApplication.getAppContext())+ " ( " +android.os.Build.MODEL+ " ) " );
                //如果验证通过...
                if (msg != null ){
                    if (msg.contains( "OK" )){
                        msgFlag = true;
                        Log.e("NetTool", "服务器IP：" + msg.substring( 8 ,msg.length()));
                        msgResult = msg.substring(2);
                    }
                }
            } else {

            }
        } catch (IOException e1) {
            e1.printStackTrace();
        } catch (InterruptedException e2) {
            e2.printStackTrace();
        } finally {
            proc.destroy();
        }
        if (linkFlag){
            if (msgFlag){
                return "1_"+msgResult;
            }
            return "2_"+current_ip;
        }
        return null;
    }


    //向serversocket发送消息
    public String sendMsg(String ip,String msg) {

        String res = null ;
        Socket socket = null ;

        try {
            socket = new Socket(ip, SERVERPORT);
            //向服务器发送消息
            PrintWriter os = new PrintWriter(socket.getOutputStream());
            os.println(msg);
            os.flush(); // 刷新输出流，使Server马上收到该字符串

            //从服务器获取返回消息
            DataInputStream input = new DataInputStream(socket.getInputStream());
            res = input.readUTF();
        } catch (Exception unknownHost) {
            System.out.println( "You are trying to connect to an unknown host!" );
        } finally {
            // 4: Closing connection
            try {
                if (socket != null ) {
                    socket.close();
                }
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
        return res;
    }



    /**
     * 过程进度
     * @param values
     */
    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
    }

    /**
     * 结果
     * @param s
     */
    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        if (s != null){
            new Handler(Looper.getMainLooper()).post(()->{
                if (netToolTaskListener != null){
                    if (s.contains("1_")){
                        netToolTaskListener.linkSuccess("ip = "+ s.substring(2));
                    }else if (s.contains("2_")){
                        netToolTaskListener.sendMsgSuccess("result = "+ s.substring(2));
                    }
                }
            });
        }
    }
    public interface NetToolTaskListener{
        void linkSuccess(String ip);
        void sendMsgSuccess(String result);
    }
}
